#coding: utf-8

import smtplib
import os
import psutil
from email.mime.text import MIMEText   #导入MIMEText类
from email.utils import formataddr

ip = psutil.net_if_addrs()     #获取IP地址
hostname  = psutil.users()  #获取主机名
cpu = psutil.cpu_count()  #获取CPU线程
mem = psutil.virtual_memory() #获取内存总量
disk = psutil.disk_partitions() #获取硬盘总大小
HOST = "smtp.qq.com"      #指定使用qq邮箱
SUBJECT = u"服务器硬件信息"   #邮件标题
TO = "xxxxxx@126.com"   #收件人
FROM = "1307215853@qq.com"    #发件人

msg = MIMEText(_text="""
                <table color="CCCC33" width="800" border="1" cellspacing="0" cellpadding="5" text-align="center">
                        <tr>
                                <td text-align="center">name</td>
                                <td text-align="center">network</td>
                                <td>CPU</td>
                                <td>Mem</td>
                                <td>Disk</td>
                        </tr>   
                        <tr>   
                                <td text-align="center">%s </td>
                                <td>%s </td>
                                <td>%s </td>
                                <td>%s </td>
                                <td>%s </td>
                        </tr>
                </table>""" % (hostname,ip,cpu,mem,disk),_subtype='html',_charset='utf-8')
msg['Subject'] = SUBJECT
msg['From'] = formataddr(["FromRunoob",FROM])
msg['To'] = formataddr(["FK",TO])
try:
        #server  = smtplib.SMTP()      #创建一个SMTP对象
        server = smtplib.SMTP_SSL(HOST,"465")      #通过connect方法链接到smtp主机
        #server.starttls()             #启动安全传输模式
        server.login("1307215853@qq.com","xxx")  # 登录qq邮箱 校验用户，密码
        server.sendmail(FROM, [TO], msg.as_string())   #发送邮件
        server.quit()
        print("邮件发送成功 %s %s %s %s %s" % (hostname,ip,cpu,mem,disk))  #发送成功并打印
except Exception as e:
        print("邮件发送失败："+str(e))